import Vue from 'vue'
import Vuex from 'vuex'
import {RootState} from "@/ts.d/interfaces/RootState";
import {Song} from "@/ts.d/classes/Song";
import {Singer} from "@/ts.d/classes/Singer";
import {AlbumItem} from "@/ts.d/classes/AlbumItem";
import {SongListItem} from "@/ts.d/classes/SongListItem";
import {ipcRenderer} from "electron";
import {events} from "@/ts.d/native/events";

Vue.use(Vuex)


export function getCache(key: string) {
  const {value, expire} = JSON.parse(localStorage.getItem(key) as string) || {}
  if(expire && expire > +new Date()){
    return value
  }else if(expire && expire < +new Date()){
    if(value){
      localStorage.removeItem(key)
    }
    return null
  }else{
    return value || null
  }
}

export function setCache(key: string, value: object | any, expire?: number | Date ) {
  localStorage.setItem(key, JSON.stringify({
    value,
    expire: expire ? +new Date(expire) : 0
  }))
}


export default new Vuex.Store<RootState>({
  state: {
    currentSong: new Song(),
    currentPlayList: [],
    history: getCache("history") ||[],
    like: getCache("like") || {
      album: [],
      singer: [],
      song: [],
      songList: [],
    },
    downloadPath: getCache("downloadPath") || "D:\\",
    localSongs:getCache("localSongs") || []
  },
  mutations: {
    setCurrentSong(state, song: Song) {
      state.currentSong = song
    },
    setCurrentPlayList(state, list) {
      state.currentPlayList = list
    },
    addHistory(state: RootState, payload: Song) {
      state.history.push(payload)
    },
    setDownloadPath(state, payload: string) {
      if(!payload.toUpperCase().startsWith("C")){
        state.downloadPath = payload
        setCache("downloadPath", payload)
      }else {
        console.log("---失败---, c盘写入文件失败")
      }
    },
    delLocalSong(state, index: number) {
      console.log(`---移除无效源---${state.localSongs[index].name}`)
      state.localSongs.splice(index, 1)
      setCache("localSongs", state.localSongs)
    }
  },
  actions: {
    nextSong(context, song: Song) {
      context.commit("setCurrentSong", song)
      const existIndex = context.state.history.findIndex(item => item.mid === song.mid)
      if(existIndex===-1){
        // context.state.history.splice(existIndex, 1)
        context.state.history.unshift(song)
        context.state.history.length > 100 && context.state.history.shift()
        setCache("history", context.state.history)
      }


    },
    toggleLike(context, obj: { type: "song" | "songList" | "singer" | "album"; item: Song | Singer | AlbumItem | SongListItem }) {
      const list = context.state.like[obj.type]
      const index = list.findIndex((item: any) => item.mid === obj.item.mid)
      index === -1 ? list.push(obj.item as any) : list.splice(index, 1)
      setCache("like", context.state.like)
    },
    download(context, meta: {url: string; fileName: string; /*文件标识*/fileSign: string| any;info: Song}) {
      return new Promise((resolve, reject) => {
        // 解析拓展名
        let ext = ""
        try{
          const ret = /\.(.+)\?.*/.exec(meta.url.split("/").slice(-1)[0]) as any
          ext = ret[1]
        }catch (e) {
          ext = "mp3"
        }
        const fileName = `${context.state.downloadPath}\\${meta.fileName}.${ext}`
        const clone = {...meta.info}
        clone.src = fileName
        context.state.localSongs.push(clone)
        ipcRenderer.invoke(events.DOWNLOAD, {url: meta.url, fileName, fileSign: meta.fileSign}).then(ret=>{
          console.log("comp", ret)
          setCache("localSongs", context.state.localSongs)
        })
      })
    },
  },
})


